package com.base.social.signature.support;

import com.base.core.utils.JacksonUtils;
import com.base.social.signature.SignatureTemplate;

import java.util.Map;
import java.util.TreeMap;

public class ElemeSignature extends SignatureTemplate {

    /**
     * 生成饿了么请求的Signature
     * <p>
     * 代码copy并修改自：https://coding.net/u/napos_openapi/p/eleme-openapi-java-sdk/git/blob/master/src/main/java/eleme/openapi/sdk/utils/SignatureUtil.java
     *
     * 参数选项
     * appKey     平台应用的授权key
     * secret     平台应用的授权密钥
     * timestamp  时间戳，单位秒。API服务端允许客户端请求最大时间误差为正负5分钟。
     * action     饿了么请求的api方法
     * token      用户授权的token
     * @param params 加密参数
     * @return Signature
     */
    @Override
    public String generateSignature(Map<String, Object> params) {
        final Map<String, Object> sorted = new TreeMap<>(params);
        StringBuffer string = new StringBuffer();
        for (Map.Entry<String, Object> entry : sorted.entrySet()) {
            string.append(entry.getKey()).append("=").append(JacksonUtils.toJSONString(entry.getValue()));
        }
        String action = sorted.get("action").toString();
        String token = sorted.get("token").toString();
        String secret = sorted.get("secret").toString();
        String splice = String.format("%s%s%s%s", action, token, string, secret);
        String calculatedSignature = md5(splice);
        return calculatedSignature.toUpperCase();
    }
}
